package myJs.cps

import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.all._
import myJs.Implicits._
import myJs.myPkg.Select2Options
import myJs.myPkg.jquery._
import myJs.tool.Tool
import org.scalajs.dom.{Event, html}
import myJs.myPkg.Hooks._

import scala.collection.immutable.SeqMap
import scala.scalajs.js
import myJs.Implicits._

import scala.scalajs.js.JSConverters._

/** Created by yz on 15/9/2023
  */
object PureSelect2MulCp {

  case class Props(
      name: String = "",
      optionMap: SeqMap[String, String],
      hasBv: Boolean = false,
      formJq: JQuery = $("#form"),
      value: js.UndefOr[List[String]] = js.undefined,
      onChange: List[String] => Callback,
      width: String = "150px",
      show: Boolean = true,
      allowClear: Boolean = false
  ){
    @inline def render: VdomElement = {
      Component(this)
    }
  }

  val Component = ScalaFnComponent[Props] { props =>

    val selectRef = Ref[html.Select]

    val placeholder = "click to choose"

    def onChange(vs: List[String]) = {
      props.onChange(vs)
    }

    useEffect(
      {
        selectRef
          .foreach { y =>
            val curJq = $(y)

            val data = props.optionMap.map { case (id, text) =>
              js.Dictionary("id" -> id, "text" -> text)
            }.toJSArray
            val options =
              Select2Options(data = data, multiple = true, placeholder = placeholder, allowClear = props.allowClear)
            curJq.mySelect2(options)
            refreshValue
            curJq.myOn(
              "select2:select select2:unselect",
              (e: Event) => {
                val vs = $(y).select2Val.toList
                onChange(vs)
              }
            )
            curJq.myOn(
              "select2:clear",
              (e: Event) => {
                val vs = $(y).select2Val.toList
                onChange(vs)
              }
            )
          }
      },
      List()
    )

    def refreshValue = {
      selectRef.foreach { y =>
        val jq = $(y)
        jq.select2Val(props.value.get.toJSArray)
      }
    }

    useEffect(
      {
        selectRef
          .foreachCB { y =>
            val jq = $(y)
            val data = props.optionMap.map { case (id, text) =>
              js.Dictionary("id" -> id, "text" -> text)
            }.toJSArray
            val options =
              Select2Options(data = data, multiple = true, placeholder = placeholder, allowClear = props.allowClear)
            jq.mySelect2(options)
            refreshValue
          }
      },
      List(props.optionMap)
    )

    useEffect(
      {
        refreshValue
      },
      List(props.value)
    )

    div(
      display := Tool.b2Display(props.show),
      select(
        className := "form-control",
        name := s"${props.name}",
        width := s"${props.width}"
      ).withRef(selectRef)
    )

  }

}
